package com.lp.zyll.security;

import com.lp.zyll.filter.JwtAuthenticationEntryPoint;
//import com.lp.zyll.filter.JwtAuthenticationTokenFilter;
import com.lp.zyll.filter.JwtAuthenticationTokenFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {


//    @Autowired
//    AuthenticationTokenFilter authenticationTokenFilter;

    @Autowired
    JwtAuthenticationEntryPoint authenticationErrorHandler;

//    @Autowired
//    JwtAccessDeniedHandler jwtAccessDeniedHandler;
//
    @Autowired
JwtAuthenticationTokenFilter authenticationTokenFilter;

//
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // CSRF禁用，因为不使用session
        http.csrf().disable()
                // 认证失败处理类
                .exceptionHandling()
                .authenticationEntryPoint(authenticationErrorHandler)
//                .accessDeniedHandler(jwtAccessDeniedHandler)
                .and()
                // 基于token，所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                // 过滤请求
                .authorizeRequests()
                //放行
                .antMatchers("/config/**",
                        "/swagger-ui/**",
                        "/",
                        "/springdoc/**"
                ).permitAll()
                .antMatchers("/auth/**").permitAll()
                //hasAnyAuthority 不用加前缀    hasAnyRole  默认加前缀ROLE_
                .antMatchers("/demo/**").hasAnyAuthority("admin","member")
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated()
                .and()
                .headers().frameOptions().disable();
        http.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
//        http.addFilterAfter(authenticationTokenFilter,UsernamePasswordAuthenticationFilter.class)
    }

}
